
package com.miracle.yuanshen;

import android.app.AlertDialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.*;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import com.alibaba.fastjson.JSON;
import com.miracle.yuanshen.util.Constants;
import com.mysql.cj.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;


class SmsObserver extends ContentObserver{

    public static final String DB_ADDRESS_ID = "address_id";
    public static final String addressFileName = "address.json";
    List<AddressInfoBean> addressInfoBeans;
    ListView listView;
    MyAdapter myAdapter;
    private String api = "http://@ip:5000/get_sms?sms={}";
    public MainActivity mContext;
    public Handler smsHandler;
    private static int id=0; //这里必须用静态的，防止程序多次意外初始化情况
    String _id;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public SmsObserver(MainActivity context, Handler handler) {
        super(handler);

        Log.i("SmsObserver-> ", "初始化");
        this.mContext = context;
        this.smsHandler = handler;

        address_list_handle();
        addListView();
        clearListView();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange);

        Log.e("SmsObserver-> ", "短信有改变 - "+uri.toString());
        Cursor mCursor = mContext.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, "date desc");

        if (mCursor == null) {
            Log.e("SmsObserver-> ", "mCursor为空");
            return;
        } else {
            if (mCursor.moveToFirst()){
                SmsInfo _smsInfo = new SmsInfo();
                int _inIndex = mCursor.getColumnIndex("_id");
                if (_inIndex != -1) {
                    _id = mCursor.getString(_inIndex);
                    _smsInfo._id=_id;
                }
                int thread_idIndex = mCursor.getColumnIndex("thread_id");
                _smsInfo.thread_id = mCursor.getString(thread_idIndex);
                Log.e("SmsObserver-> ", "id - "+id+" | thread_id - "+_smsInfo.thread_id);
                //比较id 解决重复问题
                if (id < Integer.parseInt(_id)) {
                    id = Integer.parseInt(_id);


                    int bodyIndex = mCursor.getColumnIndex("body");
                    _smsInfo.smsBody = mCursor.getString(bodyIndex);
                    int dateIndex = mCursor.getColumnIndex("date");
                    String date = mCursor.getString(dateIndex);
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    _smsInfo.date = dateFormat.format(new Date(Long.parseLong(date)));
                    int addressIndex = mCursor.getColumnIndex("address");
                    String address=   mCursor.getString(addressIndex);
                    _smsInfo.address = address;

                    Log.e("SmsObserver-> ", "短信内容: "+_smsInfo.toString());
                    if (address.indexOf("182")==0 || address.indexOf("+86182")==0 || address.indexOf("1068")==0) {
                        id = Integer.parseInt(_id);
                        Log.e("SmsObserver-> ", "号码匹配:"+address);
                        Message msg = smsHandler.obtainMessage();
                        _smsInfo.action = 0;// 0不对短信进行操作;1将短信设置为已读;2将短信删除
                        msg.obj = _smsInfo;
                        smsHandler.sendMessage(msg);

                        //发广播
                        Intent intent = new Intent("com.zl.zl_sms_monitor_DBiErICZ");
                        intent.putExtra("hello2", address);         //向广播接收器传递数据
                        mContext.sendBroadcast(intent);

                        // 发通知
                        send_notice(_smsInfo);

                        //发送到服务器
                        new Thread(new Runnable(){
                            @Override
                            public void run(){
                                getWebInfo(_smsInfo.toString());
                            }
                        }).start();
                        return;
                    }
                }
            }

        }
    }

    /**
     * 初始化服务器列表
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void address_list_handle(){
        //读取数据
        //1.从array.xml读取
        // Resources resourse = this.getResources();
        // String[] data = resourse.getStringArray(R.array.address);
        //2.从json文件读取
        String strings = JsonUtils.readJson(mContext, addressFileName);
        List<AddressInfoBean> addressInfoBeanList = null;
        try {
            addressInfoBeanList = JSON.parseArray(strings, AddressInfoBean.class);
        } catch (Exception e) {
            Log.e("SmsObserver-> ", addressFileName+" 不合法");
        } finally {
            if (addressInfoBeanList == null){
                addressInfoBeanList = new ArrayList<>();
            }
        }

        addressInfoBeans = addressInfoBeanList;
        myAdapter = new MyAdapter( mContext, R.layout.address_item, addressInfoBeans );
        listView = mContext.findViewById(R.id.address_list);
        listView.setAdapter(myAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                MyAdapter.Address_holder viewTag = (MyAdapter.Address_holder) view.getTag();
                AddressInfoBean addressInfoBean = addressInfoBeans.get(i);
                Switch address_valid = viewTag.address_valid;
                if(address_valid.isChecked()){
                    address_valid.setChecked(false);
                    //进行业务处理
                    addressInfoBean.valid = false;
                }else {
                    address_valid.setChecked(true);
                    //进行业务处理
                    addressInfoBean.valid = true;
                }
                saveAddress();
            }
        });


    }

    /**
     * 添加服务器按钮
     */
    private void addListView(){
        // 获取服务IP和刷新服务的点击事件
        Button address_btn = mContext.findViewById(R.id.address_add_btn);
        address_btn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                EditText address_address_input = mContext.findViewById(R.id.address_address_input);
                String address_tmp = address_address_input.getText().toString();
                if (address_tmp==null || address_tmp.isEmpty()){
                    Toast.makeText(mContext,"刷新失败，地址为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                // String reg = "^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$";
                // if (!address_tmp.matches(reg)){
                //     Toast.makeText(mContext,"刷新失败，地址格式错误", Toast.LENGTH_SHORT).show();
                //         return;
                // }
                if (addressInfoBeans.stream().anyMatch(e -> address_tmp.equals(e.address))){
                    Toast.makeText(mContext,"刷新失败，地址已存在", Toast.LENGTH_SHORT).show();
                    return;
                }
                AddressInfoBean addressInfoBean = new AddressInfoBean();
                addressInfoBean.id = SharedPreferenceUtils.getNextId(mContext, DB_ADDRESS_ID);
                String name = ((EditText)mContext.findViewById(R.id.address_name_input)).getText().toString();
                addressInfoBean.name = StringUtils.isEmptyOrWhitespaceOnly(name) ? addressInfoBean.id.toString() : name;
                addressInfoBean.address = address_tmp;
                addressInfoBean.valid = true;
                addressInfoBeans.add(addressInfoBean);
                myAdapter.notifyDataSetChanged();//刷新数据

                saveAddress(); //持久化
                Toast.makeText(mContext,"刷新成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 删除服务器按钮
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void clearListView(){
        // 获取服务IP和刷新服务的点击事件
        Button address_btn = mContext.findViewById(R.id.address_clear_btn);
        address_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // addressInfoBeans.clear();
                // myAdapter.notifyDataSetChanged();//刷新数据
                // saveAddress(); //持久化
                // Toast.makeText(mContext,"已清空", Toast.LENGTH_SHORT).show();

                if (addressInfoBeans.size()==0){
                    AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                            .setTitle("选择需要删除的服务")//标题
                            .setMessage("服务列表为空，不需要删除！")//内容
                            .setIcon(Constants.APP_ICON)//图标
                            .create();
                    alertDialog.show();
                }else{
                    String[] names = addressInfoBeans.stream().map(e -> e.name + " - " + e.address).toArray(String[]::new);
                    Integer[] ids = addressInfoBeans.stream().map(e -> e.id).toArray(Integer[]::new);
                    boolean[] checked = new boolean[names.length];
                    AlertDialog alertDialog5 = new AlertDialog.Builder(mContext)
                            .setTitle("选择需要删除的服务")
                            .setIcon(Constants.APP_ICON)
                            .setMultiChoiceItems(names, checked, new DialogInterface.OnMultiChoiceClickListener() {//创建多选框
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                                    checked[i] = b;
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //删除数据
                                    boolean remove_flag = false;
                                    for (int a = 0; a < checked.length; a++) {
                                        if (checked[a]) {
                                            Integer id = ids[a];
                                            Iterator<AddressInfoBean> iterator = addressInfoBeans.iterator();
                                            while (iterator.hasNext()){
                                                AddressInfoBean next = iterator.next();
                                                if (next.id.equals(id)){
                                                    iterator.remove();
                                                    if(!remove_flag){
                                                        remove_flag = true;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (remove_flag){
                                        myAdapter.notifyDataSetChanged();//刷新数据
                                        saveAddress(); //持久化
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    // Toast.makeText(mContext, "这是取消按钮", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .create();
                    alertDialog5.show();
                }
            }
        });
    }


    /**
     * 轮训转发
     * @param sms
     */
    private void getWebInfo(String sms){
        for (AddressInfoBean addressInfoBean : addressInfoBeans) {
            if (addressInfoBean.valid){
                Log.e("SmsObserver-> ", "开启的服务: "+addressInfoBean);
                new Thread(new Runnable(){
                    @Override
                    public void run(){
                        String address = addressInfoBean.address.replace("{sms}", sms);
                        Log.e("SmsObserver-> ", "请求服务: "+address);
                        try{
                            URL url = new URL(address);
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            InputStream inputStream = conn.getInputStream();
                            InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
                            BufferedReader bufferedReader = new BufferedReader(reader);
                            StringBuffer buffer = new StringBuffer();
                            String temp = null;
                            while((temp=bufferedReader.readLine()) != null){
                                buffer.append(temp);
                            }
                            bufferedReader.close();
                            reader.close();
                            inputStream.close();
                            // Toast.makeText(mContext,"发送成功", Toast.LENGTH_SHORT).show();
                        }catch(Exception e){
                            e.printStackTrace();
                            // Toast.makeText(mContext,"发送失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).start();
            } else {
                Log.e("SmsObserver-> ", "关闭的服务: "+addressInfoBean.toString());
            }

        }
    }

    /**
     * 发送通知
     * @param _smsInfo
     */
    private void send_notice(SmsInfo _smsInfo){
        String CHANNEL_ID = "chat";
        NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        //适配8.0
        if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "聊天信息",NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager.createNotificationChannel(channel);
        }
        /**
         * 注意写上 channel_id，适配8.0，不用担心8.0以下的，找不到 channel_id 不影响程序
         */
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext,CHANNEL_ID)
                .setContentTitle(_smsInfo.address)
                .setContentText(_smsInfo.smsBody)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),R.mipmap.ic_launcher))
                .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)// 屏幕可见性，锁屏时，显示icon和标题，内容隐藏
                .setNumber(999)// 自定义桌面通知数量
                .setAutoCancel(true)// 是否自动消失（点击）or mManager.cancel(mNormalNotificationId)、cancelAll、setTimeoutAfter()

        ;

        //通过 builder.build() 拿到 notification
        mNotificationManager.notify(SharedPreferenceUtils.getNextNoticeId(mContext), mBuilder.build());
    }

    /**
     * 持久化服务器数据
     */
    private void saveAddress(){
        JsonUtils.writeJson(mContext, JSON.toJSONString(addressInfoBeans), addressFileName, false);
    }


}
